<?php

class CompanyController extends Controller {
    const PAGE_SIZE=10;

    /**
     * @var string specifies the default action to be 'list'.
     */
    public $defaultAction='list';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'ajaxOnly + showgrid',
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
        array('allow',  // allow all users to perform 'list' and 'show' actions
        'actions'=>array(''),
        'users'=>array('*'),
        ),
        array('allow', // allow authenticated user to perform 'create' and 'update' actions
        'actions'=>array('create','update','showgrid','getinfo','view','getaddress','getcontact','delete','merging','list'),
        'users'=>array('@'),
        ),
        array('allow', // allow admin user to perform 'admin' and 'delete' actions
        'actions'=>array('admin'),
        'users'=>array('admin'),
        ),
        array('deny',  // deny all users
        'users'=>array('*'),
        ),
        );
    }

    /**
     * Shows a particular model.
     */
    public function actionGetInfo(){
    	$returndata = company::model()->getInfo($_GET['id']);
    	echo CJavaScript::jsonEncode($returndata);
    }
    public function actionGetAddress(){
    	if(($model = company_address::model()->findByPk($_GET['id'])))
    		echo $model->address;
    	else
    		echo "No address";
    }
	public function actionGetContact(){
    	if(($model = company_contacts::model()->findByPk($_GET['id'])))
    		echo '('.$model->type.')'.$model->ref;
    	else
    		echo "No contact";
    }
    public function actionShowGrid(){
    	$model = new company('search');
        if(isset($_GET['searchText']))
            $model->cname = $_GET['searchText'];
        echo $this->renderPartial('_choose',array('model'=>$model),true, true);
    }
    public function actionAutoCompleteName() {
        $criteria = new CDbCriteria;
        $returnVal=array();
        $criteria->condition = "cname like :cname";
        $criteria->order = "cname asc";
        $criteria->limit = 10;
        $criteria->params = array(":cname"=>$_GET['term']);
        $company = company::model()->find($criteria);
        if($company != null) {
            $returnVal[] = array('label'=>$company->cname,'id'=>$company->id,'value'=>$company->cname);
        }
        
        $criteria->params = array(":cname"=>$_GET['term']."%");
        $company = company::model()->findAll($criteria);
        foreach($company as $c) {
            $returnVal[] = array('label'=>$c->cname,'id'=>$c->id,'value'=>$c->cname);
        }
        $returnVal[] = array('label'=>'Add new contact','id'=>-1,'value'=>$_GET['term']);
        echo CJSON::encode($returnVal);
    }
    public function actionView() {
        $this->render('view',array('model'=>$this->loadcustomer()));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'show' page.
     */
	public function actionMerging(){
		$model = $this->loadcustomer();
		if(isset($_GET['searchText']))
			$model->cname = $_GET['searchText'];

		if(isset($_GET['merge_id'])) {
			$id = $_GET['merge_id'];
			$transaction = Yii::app()->db->beginTransaction();
			$ajax = (Yii::app()->request->isAjaxRequest)?true:false;
			try {
				foreach($id as $_id) {
					if($_id != $model->id) {
						if(cargo::model()->updateAll(array('shipper_id'=>$model->id),'shipper_id=:shipper_id',array(':shipper_id'=>$_id))===false)
							throw new Exception('Shipper error '.$_id);
						if(cargo::model()->updateAll(array('consignee_id'=>$model->id),'consignee_id=:shipper_id',array(':shipper_id'=>$_id))===false)
							throw new Exception('consignee error '.$_id);
						if(company_address::model()->updateAll(array('company_id'=>$model->id),'company_id =:company_id',array(':company_id'=>$_id))===false)
							throw new Exception('address error '.$_id);
						if(company::model()->deleteAll('id=:id',array(':id'=>$_id))===false)
							throw new Exception('delete error '.$_id);
					
					}
				}
				
				$transaction->commit();
			}
			catch(Exception $e) {
				$transaction->rollback();
				if($ajax){
            		echo CJavaScript::jsonEncode(array('error'=>$e->getMessage()));
            		Yii::app()->end();
            	}
            	echo $e->getMessage();
			}	
			if($ajax) {
				echo CJavaScript::jsonEncode(array('id'=>$model->id));
				Yii::app()->end();
			}
			else
				$this->redirect(array('/company/view','id'=>$model->id));
			
		}
		if(Yii::app()->request->isAjaxRequest) {
			echo $this->renderPartial('_grid',array('model'=>$model),true,true);
			Yii::app()->end();
		}
		$this->render('_grid',array(
			'model'=>$model,
		));
				
	}
	private function mergeCompany($newID){
		if(!isset($_GET['merge_id']))
			return;
		$id = implode(',',$_GET['merge_id']);
		cargo::model()->updateAll(array('shipper_id'=>$newID,'shipper_id in (:shipper_id)',array(':shipper_id'=>$id)));
		cargo::model()->updateAll(array('consignee_id'=>$newID,'consignee_id in (:shipper_id)',array(':shipper_id'=>$id)));
		company_address::model()->updateAll(array('company_id'=>$newID,'company_id in (:company_id)',array(':company_id'=>$id)));		
	}
    public function actionCreate() {
    	$model = new company;
    	
        if(isset($_POST['company'])) {
            $model->attributes = $_POST['company'];
            $this->validateModels($model);
            if($model->save()){
            	if(Yii::app()->request->isAjaxRequest){
            		echo CJavaScript::jsonEncode(array('id'=>$model->id));
            		Yii::app()->end();
            	}
            	else
            		$this->redirect(array('view','id'=>$model->id));
            }
        }
        
        if(Yii::app()->request->isAjaxRequest) {
            echo $this->renderPartial('create',array('model'=>$model),true,true);
            Yii::app()->end();
        }
        else
            $this->render('create',array('model'=>$model,'update'=>false));
    }
    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'show' page.
     */
    public function actionUpdate() {
        $model = $this->loadcustomer();
        if(isset($_POST['company'])) {
            $model->attributes=$_POST['company'];
            $this->validateModels($model);
            if($model->save()){
            	if(Yii::app()->request->isAjaxRequest){
            		echo CJavaScript::jsonEncode(array('id'=>$model->id));
            		Yii::app()->end();
            	}
            	else
            		$this->redirect(array('view','id'=>$model->id));
            }
        }
        if(Yii::app()->request->isAjaxRequest) {
            echo $this->renderPartial('update',array('model'=>$model),true,true);
            Yii::app()->end();
        }
        else
            $this->render('update',array('model'=>$model,'update'=>false));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'list' page.
     */
    public function actionDelete() {
        if(Yii::app()->request->isPostRequest) {
        // we only allow deletion via POST request
        	$model = $this->loadcustomer();
        	if($model->cargo == null) {
            	if($model->delete()) {
            		company_address::model()->deleteAll('company_id=:id',array(':id'=>$model->id));
            		company_contacts::model()->deleteAll('company_id=:id',array(':id'=>$model->id));
            		company_email::model()->deleteAll('company_id=:id',array(':id'=>$model->id));
            	}
            	if(!Yii::app()->request->isAjaxRequest)
            		$this->redirect(array('list'));
        	}
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionList() {
        $model = new company;
    	if(isset($_GET['searchText']))
    		$model->searchText = $_GET['searchText'];
		$this->render('list',array(
			'model'=>$model,
		));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $this->processAdminCommand();

        $criteria=new CDbCriteria;

        $pages=new CPagination(customer::model()->count($criteria));
        $pages->pageSize=self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort=new CSort('customer');
        $sort->applyOrder($criteria);

        $models=customer::model()->findAll($criteria);

        $this->render('admin',array(
            'models'=>$models,
            'pages'=>$pages,
            'sort'=>$sort,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadcustomer($id=null) {
        if($this->_model===null) {
            if($id!==null || isset($_GET['id']))
                $this->_model=company::model()->findbyPk($id!==null ? $id : $_GET['id']);
            
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Executes any command triggered on the admin page.
     */
    protected function processAdminCommand() {
        if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete') {
            $this->loadcustomer($_POST['id'])->delete();
            // reload the current page to avoid duplicated delete actions
            $this->refresh();
        }
    }
}
